import sys, time, hashlib, base64, requests
from jinja2 import Environment, FileSystemLoader
from selenium import webdriver
from collections import defaultdict

# 根据simplesheet和cnv_stat.xls生成cnv.Stats.xls和cnv.Stats.html
def html_set_data(texdata, outprefix):
    path_dir = '/' + '/'.join(outprefix.split('/')[1:-1])
    env = Environment(loader=FileSystemLoader('/home/zhengzhiqiang/workflow/qcstat/'))
    template = env.get_template('tempQCcnv.html')
    buf = template.render(texdata)
    html = f'{outprefix}.cnv.Stats.html'
    with open(html, "w", encoding="utf-8") as fp:
        fp.write(buf)
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_argument('--disable-dev-shm-usage')
    browser = webdriver.Chrome(options=chrome_options)
    browser.get(f'file://{html}')
    time.sleep(3)
    browser.quit()

    # try:
    #     url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c635edcf-1adb-4277-9152-060d661c20b7'
    #     name = outprefix.split('/')[-1]
    #     name1=f"{name}-CNV"
    #     requests.post(url, json={"msgtype": "text", "text": {"content": f"{name1}"}})
    #               #fastqcnv.stats.png
    #     with open('fastqcnv.stats.png', 'rb') as fq:
    #         png = fq.read()
    #         md5 = hashlib.md5(png).hexdigest()
    #         b64 = base64.b64encode(png).decode('utf-8')
    #         data = {'msgtype': 'image','image': {'base64': b64,'md5': md5}}
    #         requests.post(url, json=data)
    # except Exception as e:
    #     print(e)
    #     sys.exit('PNG is not exists!')


with open(sys.argv[1]) as csv, open(sys.argv[2]) as stat, open(sys.argv[3]+'.cnv.Stats.xls', 'w') as out:
    need_sample=[]
    flag = 0
    sample = {}
    for i in csv:
        if flag == 0:
            if i.startswith('Sample_ID'):
                flag = 1
            else:
                continue
            continue
        if flag == 1:
            x = i.split(',')
            if x[0].startswith('BY'):
                sample[f'Barcode{x[4]}'] = x[0]
                need_sample.append(f"Barcode{x[4]}")
    stat.readline()
    outdata = {'tabledata1': []}
    outdata['tabledata1'].append({'sampleID': 'sampleID', 'tindex': 'index', 'treadsNumber': 'readsNumber'})
    out.write('sampleID\tindex\treadsNumber\n')
    flag=1
    for i in stat:
        #if i not in need_sample:continue
        x = i.strip().split('\t')
        if x[0] not in need_sample:continue
        if x[0].find('otherindex') > -1:continue
#            out.write(f'{x[0]}\t{x[0]}\t{int(x[1]):,}\n')
#            if int(x[1]) > 15_000_000:
#                outdata['tabledata1'].append({'sampleID': f'{x[0]}', 'tindex': f'{x[0]}', 'treadsNumber': f'{int(x[1]):,}', 'OIflag': True})
#            else:
#                outdata['tabledata1'].append({'sampleID': f'{x[0]}', 'tindex': f'{x[0]}', 'treadsNumber': f'{int(x[1]):,}', 'OIflag': False})
        elif x[0].find('undecoded') > -1:continue
#            out.write(f'{x[0]}\t{x[0]}\t{int(x[1]):,}\n')
#            if int(x[1]) > 75_000_000:
#                outdata['tabledata1'].append({'sampleID': f'{x[0]}', 'tindex': f'{x[0]}', 'treadsNumber': f'{int(x[1]):,}', 'UDflag': True})
#            else:
#                outdata['tabledata1'].append({'sampleID': f'{x[0]}', 'tindex': f'{x[0]}', 'treadsNumber': f'{int(x[1]):,}', 'UDflag': False})
        elif x[0] == 'TotalReads':continue
#            out.write(f'{x[0]}\t{x[0]}\t{int(x[1]):,}\n')
#            if int(x[1]) < 600_000_000:
#                outdata['tabledata1'].append({'sampleID': f'{x[0]}', 'tindex': f'{x[0]}', 'treadsNumber': f'{int(x[1]):,}', 'TTflag': True})
#            else:
#                outdata['tabledata1'].append({'sampleID': f'{x[0]}', 'tindex': f'{x[0]}', 'treadsNumber': f'{int(x[1]):,}', 'TTflag': False})
        elif sample[x[0]].startswith('NC'):continue
#            out.write(f'{sample[x[0]]}\t{x[0]}\t{int(x[1]):,}\n')
#            if int(x[1]) > 5_000_000:
#                outdata['tabledata1'].append({'sampleID': sample[x[0]], 'tindex': x[0], 'treadsNumber': f'{int(x[1]):,}', 'NCflag': True})
#            else:
#                outdata['tabledata1'].append({'sampleID': sample[x[0]], 'tindex': x[0], 'treadsNumber': f'{int(x[1]):,}', 'NCflag': False})
        else:
            if int(x[1]) > 15000000 or sample[x[0]].find('-YF') > -1 or sample[x[0]].find('-KY') > -1 or sample[x[0]].find('-SY') > -1:
                bit15M = False
            else:
                bit15M = True
            out.write(f'{sample[x[0]]}\t{x[0]}\t{int(x[1]):,}\n')
            outdata['tabledata1'].append({'sampleID': sample[x[0]], 'tindex': x[0], 'treadsNumber': f'{int(x[1]):,}', 'bit15M': bit15M})

if len(outdata["tabledata1"])==1:
    print("No BY samples")
else:
    html_set_data(outdata, sys.argv[3])
